package com.lw.common.utils;

import org.springframework.stereotype.Service;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;

@Service
public class LoginAttemptService {
    private final int MAX_ATTEMPT = 5; // 最大尝试次数
    private final Cache cache; // 缓存对象

    public LoginAttemptService(CacheManager cacheManager) {
        this.cache = cacheManager.getCache("loginAttemptsCache");
    }

    public void loginFailed(String key) {
        int attempts = getAttempts(key) + 1;
        cache.put(key, attempts);
    }

    public boolean isBlocked(String key) {
        return getAttempts(key) >= MAX_ATTEMPT;
    }

    private int getAttempts(String key) {
        return cache.get(key, Integer.class) == null ? 0 : cache.get(key, Integer.class);
    }

    public void loginSucceeded(String key) {
        cache.evict(key);
    }
    /**
     * 剩余尝试次数
     * @param username 用户名
     * @return  剩余登录尝试次数
     */
    public int hasTimes(String username) {
        return GlobalConstants.LOGIN_ERROR_MAX_ATTEMPT -  getAttempts(username) + 1 ;
    }
}
